package org.feng.navigation.web.config;

import lombok.NonNull;
import org.feng.navigation.common.util.StringUtil;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 日志堆栈拦截：设置 businessId
 *
 * @version V1.0
 * @author: junzi
 * @date: 2023年01月12日 11时18分
 */
@Component
public class TraceInterceptor implements HandlerInterceptor {

    private static final String BUSINESS_ID = "businessId";

    @Override
    public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        String businessId = request.getHeader(BUSINESS_ID);
        if (StringUtils.hasLength(businessId)) {
            MDC.put(BUSINESS_ID, businessId);
        } else {
            MDC.put(BUSINESS_ID, StringUtil.uuid());
        }
        return true;
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, Exception ex) {
    }
}
